package com.bwei.topnews.base;

import android.text.TextUtils;

import com.bwei.topnews.app.MyApplication;
import com.bwei.topnews.utils.CommonUtils;
import com.bwei.topnews.utils.MD5Encoder;
import com.bwei.topnews.utils.NetUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Created by qwe on 2016/11/1.
 */
public abstract class BaseData {

    private static final String TAG = "BaseData";
    private BufferedReader bufferedReader;
    // 网络错误
    public static final int Error_Net = 100;
    //请求错误
    public static final int Error_Request=200;
    // 请求时间
    public static final  long LONGTTIME=1000*60*60*72;
    public static final  long SHORTTIME=1000*60*10;
    public static final  long NOTIME=0;

    public void getData(String path, long time){
        //先看本地是否有数据
        String dataFromLocal = getDataFromLocal(path, time);
        if(TextUtils.isEmpty(dataFromLocal)){
            getDataFromNet(path, time);
        }else{
            setResultData(dataFromLocal);
        }

    }

    public abstract void setResultData(String data);

    public abstract void setFailResult(int error_Net);

    private void writeDataToLocal(String json,String path,long time){
        BufferedWriter bufferedwriter=null;
        try {
            File cacheDir = MyApplication.getContext().getCacheDir();
            File file = new File(cacheDir, MD5Encoder.encode(path));
            bufferedwriter = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
            bufferedwriter.write(System.currentTimeMillis()+ "\r\n");
            bufferedwriter.write(json);
            bufferedwriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(bufferedwriter!=null){
                try {
                    bufferedwriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void getDataFromNet(final String path, final long time) {
        int netWorkType = NetUtils.getNetWorkType(MyApplication.getContext());
        if(netWorkType!=NetUtils.NETWORKTYPE_INVALID){
            RequestParams requesParams = new RequestParams(path);
            // 证明有网，开始网络请求
            x.http().get(requesParams, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(final String json) {
                    setResultData(json);
                    // 写入本地
                CommonUtils.executeRunnable(new Runnable() {
                    @Override
                    public void run() {
                        writeDataToLocal(json,path,time);
                    }
                });
            }

                @Override
                public void onError(Throwable throwable, boolean b) {
                        setFailResult(Error_Request);
                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onFinished() {

                }
            });
        }else{
            // 网络问题
            setFailResult(Error_Net);
        }


    }

    private String getDataFromLocal(String path, long time) {

        try {
            File cacheDir = MyApplication.getContext().getCacheDir();
            File file =  new File(cacheDir, MD5Encoder.encode(path));
            bufferedReader = new BufferedReader(new FileReader(file.getAbsolutePath()));
            // 之前时间+有效时间
            long t = Long.parseLong(bufferedReader.readLine());
            //在有效时间之内
            if(System.currentTimeMillis()-t<time){
                StringBuilder stringBuilder = new StringBuilder();
                String line = null;
                while((line = bufferedReader.readLine())!=null){
                    stringBuilder.append(line);
                }
                return  stringBuilder.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(bufferedReader!=null){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
